package com.cykj.pos.service.impl;

import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.vo.SettlementVO;
import com.cykj.pos.mapper.BizMerchantMapper;
import com.cykj.pos.mapper.SettlementRateTemplateMapper;
import com.cykj.pos.mapper.ToolCashbackTemplateMapper;
import com.cykj.pos.service.IBizPosMachineService;
import com.cykj.pos.util.PublicUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import com.cykj.pos.mapper.AllocationRelationMapper;
import com.cykj.pos.service.IAllocationRelationService;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 划拨-机具层级关系Service业务层处理
 *
 * @author weijianbo
 * @date 2025-01-20
 */
@Service
public class AllocationRelationServiceImpl extends ServiceImpl<AllocationRelationMapper, AllocationRelation> implements IAllocationRelationService {

    @Resource
    private AllocationRelationMapper allocationRelationMapper;

    @Resource
    private BizMerchantMapper merchantMapper;

    @Resource
    private SettlementRateTemplateMapper settlementRateTemplateMapper;

    @Resource
    private ToolCashbackTemplateMapper toolCashbackTemplateMapper;

    @Resource
    private IBizPosMachineService iBizPosMachineService;


    @Override
    public List<AllocationRelation> queryList(AllocationRelation allocationRelation) {
        LambdaQueryWrapper<AllocationRelation> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(allocationRelation.getPosSn())){
            lqw.eq(AllocationRelation::getPosSn ,allocationRelation.getPosSn());
        }
        if (allocationRelation.getSettlementId() != null){
            lqw.eq(AllocationRelation::getSettlementId ,allocationRelation.getSettlementId());
        }
        if (allocationRelation.getMerchId() != null){
            lqw.eq(AllocationRelation::getMerchId ,allocationRelation.getMerchId());
        }
        if (StringUtils.isNotBlank(allocationRelation.getMerchName())){
            lqw.like(AllocationRelation::getMerchName ,allocationRelation.getMerchName());
        }
        return this.list(lqw);
    }

    @Override
    public AllocationRelation selectInfoBySnAndMerchId(String sn, Long merchId) {
        return allocationRelationMapper.selectInfoBySnAndMerchId(sn,merchId);
    }

    @Override
    public AjaxResult checkMySnCount(AllocationRelation allocationRelation) {
        BizMerchant bizMerchant = merchantMapper.selectInfoByUserId(allocationRelation.getUserId());
        int count = allocationRelationMapper.getMySnCount(bizMerchant.getMerchId());
        if(count != 0){
            count = 1;
        }
        return AjaxResult.success("是否有设备",count);// 0没设备, 1 有设备
    }

    public static void main(String[] args) {
        new BigDecimal(4).divide(new BigDecimal(9),2,BigDecimal.ROUND_DOWN);
    }

    @Override
    public AjaxResult myPolicy(String paramJson) {
        AjaxResult ajaxResult = AjaxResult.success("我的政策");
        Map<String, String> map = PublicUtil.generateMap(paramJson);
        Long userId = Long.parseLong(map.get("userId"));
        System.out.println("userId"+userId);
        BizMerchant bizMerchant = merchantMapper.selectInfoByUserId(userId);
        // 团队总设备数
        int allSnCount = allocationRelationMapper.getMyTeamSnCount(bizMerchant.getMerchId());
        // 团队总激活数
        int activeSnCount = allocationRelationMapper.getMyTeamActiveSnCount(bizMerchant.getMerchId());
        // 激活率
        BigDecimal rate = BigDecimal.ZERO;
        if(activeSnCount != 0){
            rate= new BigDecimal(activeSnCount).divide(new BigDecimal(allSnCount),2,BigDecimal.ROUND_DOWN);
        }
        //我的结算政策
        List<SettlementVO> voList = allocationRelationMapper.getMySettlementPolicy(bizMerchant.getMerchId());
        // 机具政策
        List<SettlementVO> feeList = allocationRelationMapper.getDefaultFlowFeePolicy();
        //提现政策
        List<String> listWithdrawalPolicy = new ArrayList<>();
        listWithdrawalPolicy.add("默认政策");
        //提现分润政策
        List<String> listProfitPolicy = new ArrayList<>();
        listProfitPolicy.add("提现分润政策");
        ajaxResult.put("allSnCount",allSnCount);
        ajaxResult.put("activeSnCount",activeSnCount);
        ajaxResult.put("rate",rate);
        ajaxResult.put("voList",voList);
        ajaxResult.put("feeList",feeList);
        ajaxResult.put("listWithdrawalPolicy",listWithdrawalPolicy);
        ajaxResult.put("listProfitPolicy",listProfitPolicy);
        System.out.println(ajaxResult);
        return ajaxResult;
    }

    @Override
    public AjaxResult backMySettlementPolicy(String paramJson) {
        Map<String, String> map = PublicUtil.generateMap(paramJson);
        Long settlementId = Long.parseLong(map.get("settlementId"));
        SettlementRateTemplate settlementRateTemplate = settlementRateTemplateMapper.selectById(settlementId);
        return AjaxResult.success("我的结算政策",settlementRateTemplate);
    }

    @Override
    public AjaxResult backMyCashbackPolicy(String paramJson) {
        Map<String, String> map = PublicUtil.generateMap(paramJson);
        Long settlementId = Long.parseLong(map.get("settlementId"));
        ToolCashbackTemplate toolCashbackTemplate = toolCashbackTemplateMapper.selectById(settlementId);
        return AjaxResult.success("我的返现政策",toolCashbackTemplate);
    }

    @Override
    public AjaxResult backMyWithdrawalPolicy() {
        WithdrawalRateTemplate withdrawalRateTemplate = merchantMapper.getDefaultWithdrawalTemplate();
        return AjaxResult.success("提现政策",withdrawalRateTemplate);
    }

    @Override
    public AjaxResult backMyWithdrawalProfitPolicy(String paramJson) {
        Map<String, String> map = PublicUtil.generateMap(paramJson);
        Long userId = Long.parseLong(map.get("userId"));
        BizMerchant bizMerchant = merchantMapper.selectInfoByUserId(userId);
        WithdrawalRateTemplate withdrawalRateTemplate = new WithdrawalRateTemplate();
        withdrawalRateTemplate.setProfitRate(bizMerchant.getWithdrawalRate());
        withdrawalRateTemplate.setProfitFee(bizMerchant.getWithdrawalFee());
        withdrawalRateTemplate.setRewardRate(bizMerchant.getRewardWithdrawalRate());
        withdrawalRateTemplate.setRewardFee(bizMerchant.getRewardWithdrawalFee());
        WithdrawalRateTemplate withdrawalRateTemplate1 = merchantMapper.getWithdrawalData(String.valueOf(bizMerchant.getWithdrawalId()));
        withdrawalRateTemplate.setVar1(withdrawalRateTemplate1.getVar1());
        return AjaxResult.success("提现分润政策",withdrawalRateTemplate);
    }

    @Override
    public AllocationRelation getInfoBySnAndMerchId(String posCode, Long merchId) {
        return allocationRelationMapper.selectInfoBySnAndMerchId(posCode,merchId);
    }

    @Override
    public Double getRelationByMaxLevelAndSn(String posCode) {
        return allocationRelationMapper.getRelationByMaxLevelAndSn(posCode);
    }

    @Override
    public void deleteGreaterThanMyLevel(String sn, Long level) {
        allocationRelationMapper.deleteGreaterThanMyLevel(sn,level);
    }

    @Override
    public void deleteBySn(String sn) {
        allocationRelationMapper.deleteBySn(sn);
    }

    @Override
    public AllocationRelation selectGreaterThanMyLevel(String sn, Long level) {
        return allocationRelationMapper.selectGreaterThanMyLevel(sn,level);
    }

    @Override
    public AjaxResult updateFlow() {
        List<String> posSns = iBizPosMachineService.getPosByMerchIds();

        LambdaQueryWrapper<AllocationRelation> lqw = Wrappers.lambdaQuery();
        lqw.in(AllocationRelation::getPosSn,posSns);
        lqw.in(AllocationRelation::getMerchId,3337,3346);
        List<AllocationRelation> allocationRelationList = this.list(lqw);

        System.out.println(allocationRelationList.size());
        int k = 0;
        for(AllocationRelation allocationRelation : allocationRelationList){
                allocationRelation.setFortyEight(new BigDecimal(48));
                allocationRelation.setFiftyEight(new BigDecimal(58));
                allocationRelation.setSixty(new BigDecimal(60));
                allocationRelation.setFortyEight(new BigDecimal(48));
                allocationRelation.setFortyEight(new BigDecimal(48));
                allocationRelation.setFortyEight(new BigDecimal(48));
                allocationRelation.setFortyEight(new BigDecimal(48));
                allocationRelation.setFortyEight(new BigDecimal(48));



//            BizPosMachine bizPosMachine = iBizPosMachineService.getPosMachineBySnCode(allocationRelation.getPosSn());
//            if("0".equals(bizPosMachine.getSimAmt())){
//                System.out.println(allocationRelation.getPosSn()+"的流量费是"+bizPosMachine.getSimAmt()+"--> next");
//                continue;
//            }
//            System.out.println(allocationRelation.getPosSn()+"的流量费是"+bizPosMachine.getSimAmt());
//            if("48".equals(bizPosMachine.getSimAmt())){
//                System.out.println(allocationRelation.getPosSn()+"存入fortyEight");
//                allocationRelation.setFortyEight(allocationRelation.getSimFee());
//            }
//            if("60".equals(bizPosMachine.getSimAmt())){
//                System.out.println(allocationRelation.getPosSn()+"存入sixty");
//                allocationRelation.setSixty(allocationRelation.getSimFee());
//            }
//            if("68".equals(bizPosMachine.getSimAmt())){
//                System.out.println(allocationRelation.getPosSn()+"存入sixtyEight");
//                allocationRelation.setSixtyEight(allocationRelation.getSimFee());
//            }
            System.out.println(k++);
            this.saveOrUpdate(allocationRelation);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult executeHandleEdit(AllocationRelation allocationRelation) {
        //更新数据
        allocationRelationMapper.updateValueByFieldAndId(allocationRelation);
        //保留记录
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String loginUser = sysUser.getUserName();
        String content = "更新内容:将行"+allocationRelation.getId()+"字段"+allocationRelation.getField()+"值更新为"+allocationRelation.getValue();
        allocationRelationMapper.updateRecords(loginUser,content);
        return AjaxResult.success();
    }
}
